package cn.xiaov.controller;

import cn.xiaov.domain.Department;
import cn.xiaov.domain.Employee;
import cn.xiaov.service.DepartmentService;
import cn.xiaov.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    @Autowired
    DepartmentService departmentService;

    @RequestMapping("/emps")
    public String toEmpList(Model model) {
        Map<Integer, String> dept = new HashMap<>();
        List<Employee> employees = employeeService.findAll();
        for (Employee emp :
                employees) {
            Department department = departmentService.findById(emp.getDpid());
            dept.put(department.getId(), department.getDname());
        }
        model.addAttribute("emps", employees);
        model.addAttribute("dept", dept);
        return "emp/list";
    }

    @RequestMapping("/emp/toadd")
    public String toEmpAdd(Model model) {
        List<Department> departments = departmentService.findAll();
        model.addAttribute("departments", departments);
        return "emp/add";
    }

    @RequestMapping("/emp/add")
    public String addEmp(Employee employee) {
        employeeService.save(employee);
        return "redirect:/emps";
    }

    @RequestMapping("/emp/delete/{id}")
    public String deleteEmp(@PathVariable("id") Integer id) {
        employeeService.delete(id);
        return "redirect:/emps";
    }

    @RequestMapping("/emp/update/{id}")
    public String toUpdateEmp(@PathVariable("id") Integer id, Model model) {
        Employee employee = employeeService.findById(id);
        List<Department> departments = departmentService.findAll();
        model.addAttribute("emp", employee);
        model.addAttribute("departments", departments);
        return "emp/update";
    }


    @RequestMapping("/emp/update")
    public String updateEmp(Employee employee) {
        employeeService.update(employee);
        return "redirect:/emps";
    }

}
